<template>
    <div id="installOrUpgradePage">
        <div class="page-div">
          <div id="pageListDiv" class="page-list">			
							<PageListItem />		
					</div>
          <div id="pageSetDiv" class="page-set" >
            <PageSetItem />
          </div>
        </div>
        <div id="operatorDiv" class="page-operator">
            <span @click="savePageInfo" v-if="packageComplete">保存设置</span>
            <span><a :href="downloadAllURL" target="_blank">批量下载图片</a></span>
            <span @click="previewPage" v-if="false">预览效果</span>
            <span @click="beforeExecute('preview')" v-if="packageComplete" title="预览包运行时仅可查看安装过程界面和动画效果，不会安装应用">打包预览安装包</span>
            <span @click="beforeExecute('online')" v-if="packageComplete" title="正式包运行时会安装应用">打包在线安装包</span>    
            <span @click="beforeExecute('full')" v-if="packageComplete" title="正式包运行时会安装应用">打包离线安装包</span>    
            <span @click="beforeExecute('mfu_full')" v-if="packageComplete" title="将生成一个MFU文件，仅用于更新应用模板">打包升级包</span>           
            <span @click="vewPackagingProgress" v-if="!packageComplete">查看打包进度</span>
        </div>
        <ModalItem ref="modal">
            <PreviewPage v-if="dialogContent == 'preview'" />
            <PackagingProgress v-if="dialogContent == 'packagingProgress'" :step="step" @cancelPackaging="cancelPackaging"/>
        </ModalItem>
    </div>
</template>

<script>

import PageListItem from '../components/PageListItem'
import PageSetItem from '../components/PageSetItem'
import packagingUtil from '../packagingUtil.js'
import ModalItem from '../components/ModalItem'
import PreviewPage from './PreviewPage'
import ProgressBar from '../components/ProgressBar'
import PackagingProgress from './PackagingProgress'

export default {
  name: 'installOrUpgradePage',
  props:[''],
  components: {PageListItem, PageSetItem, ModalItem, PreviewPage,ProgressBar,PackagingProgress},
  data () {
    return {
       dialogContent: '',
       step: 1,
       packageComplete: true,
       interval: null,
       intervalTime: 6000,
       packageType: '',
       logPercentNum : 46 //打包日志总共有4665行输出
    }
  },
  created(){
    this.getPackagingStatus().then(res =>{
      if(res){
        res = this.clearBr(res + "");
        if(res == 'complete' || res == 'fail' || res == 'cancel'){
          this.packageComplete = true;
        }else if(res == 'start'){
          this.step = 5;
          this.packageComplete = false;
        }
        else{
          this.packageComplete = false;
          var logCount = parseInt(res);
          this.step = Math.round(logCount/this.logPercentNum);
          if(this.step >= 100){
            this.step = 99;
          }/*else if(this.step <= 20){
              this.step = 20
          }*/
        }
      }else{
        this.packageComplete = true;
      }
    });
  },
  mounted(){
    var self = this;
    $.validator.setDefaults({
        submitHandler: function() { 
            self.saveBaseInfo();
            return false;
        }
    });
  },
  methods: {
      formSubmit(){
        $("#pageSetForm").submit();
      },
      savePageInfo (){
        if(!this.checkPageInfo()){
            return;
        }
        wait();
        packagingUtil.saveProductInfo(this.$store.state.productInfo,this.$store.state.spaceId,this).then((res) => {
          this.$store.commit("getProductInfo");
          this.$store.commit("updateModifyStatus",false);
          jdiclose();
          packagingUtil.myAlert("保存成功","提示",this);     
        })
      },
      checkProductBaseInfo(){
        var productInfo = this.$store.state.productInfo;
        if(!productInfo.productName){
           packagingUtil.myAlert("产品基本信息-名称不能为空","提示",this);
           return false;
        }else if(!productInfo.productEName){
          packagingUtil.myAlert("产品基本信息-英文名称不能为空","提示",this);
          return false;
        }else if(!productInfo.appId){
          packagingUtil.myAlert("产品基本信息-AppId不能为空","提示",this);
          return false;
        }else if(!productInfo.version){
          packagingUtil.myAlert("产品基本信息-版本号不能为空","提示",this);
          return false;
        }/*else if(!productInfo.author){
          packagingUtil.myAlert("产品基本信息-作者不能为空","提示",this);
          return false;
        }else if(!productInfo.contactWay){
          packagingUtil.myAlert("产品基本信息-联系方式不能为空","提示",this);
          return false;
        }*/else if(!productInfo.description){
          packagingUtil.myAlert("产品基本信息-说明不能为空","提示",this);
          return false;
        }
        return true;
      },
      checkPageInfo(){
          var pageList = this.$store.state.productInfo[this.$store.state.activeOption].pages.page;
          for(var i = 0 ; i < pageList.length ; i ++){
              if(pageList[i].pageType == '1'){
                  if(!pageList[i].pageName){
                    packagingUtil.myAlert("第" + (i + 1) + "个页面的名称不能为空","提示",this);
                    return false;
                  }else if(!pageList[i].stayTime){
                    packagingUtil.myAlert("第" + (i + 1) + "个页面的轮播时间不能为空","提示",this);
                    return false;
                  }else{
                      try{
                          var stayTime = Number(pageList[i].stayTime);
                          if(!Number.isInteger(stayTime)){
                            packagingUtil.myAlert("第" + (i + 1) + "个页面的轮播时间必须为整数","提示",this);
                            return false;
                          }
                      }catch(e){
                        packagingUtil.myAlert("第" + (i + 1) + "个页面的轮播时间必须为整数","提示",this);
                        return false;
                      }
                  }
              }
          }
          return true;
      },
      getProductVersion(packageType){
        var self = this;
        return new Promise(function(resolve, reject) {
            self.$axios({
              // url:'/magicflu/service/s/json/'+ self.$store.state.spaceId +'/packages/feed?start=0&limit=1&bq=' + encodeURIComponent('and(version,orderby,desc)and(packageType,like_and,' + packageType + ')') ,
              url:'/magicflu/service/s/json/'+ self.$store.state.spaceId +'/packages/feed?start=0&limit=1&bq=' + encodeURIComponent('and(version,orderby,desc)') ,
              method:'get',
              responseType: 'json'
            }).then(function(response) {
              if(response.data.entry.length >0){
                  var packageInfo = response.data.entry[0];
                  if(packageInfo.version >= self.$store.state.productInfo.version){
                    resolve(packageInfo.version);
                  }else{
                    resolve("");
                  }
                  
              }else{
                resolve("");
              }
            }).catch( function(response) {
              resolve();
            });
        })
      },
      beforeExecute (type){
        if(type == 'full'){
          this.logPercentNum = 46;
          this.intervalTime = 5000;
        }else if(type == 'preview'){
          this.logPercentNum = 30;
          this.intervalTime = 1000;
        }else if(type == 'mfu_full'){
          this.logPercentNum = 30;
          this.intervalTime = 1000;
        }
        var packageType = (this.$store.state.activeOption == 'installPage' ? 'install': 'upgrade' );
        if(!this.checkProductBaseInfo()){
            return;
        }
        if(!this.checkPageInfo()){
            return;
        }
        wait();
        if(type == 'full' || type == 'mfu_full' || type == 'online'){
          this.getProductVersion(type).then((res) => {
            var lastVersion = res;
            if(lastVersion){
              //lastVersion = lastVersion.split(".").join("");
              //lastVersion = (parseInt(lastVersion) + 1) + "";
              //lastVersion = lastVersion.substring(0,1) + "." + lastVersion.substring(1,2) + "." + lastVersion.substring(2,3) + "." + lastVersion.substring(3,7);
              var tempNumArray = lastVersion.split(".");
              var num = (parseInt(tempNumArray[3]) + 1) + "";
              var OLength = tempNumArray[3].length;
              var newNum = num;
              if(num.length < OLength){
                  var temp = OLength- num.length;
                  for(var i = 0 ; i < temp; i ++){
                      newNum = '0' + newNum;
                  }
              }
              lastVersion = tempNumArray[0] + "." + tempNumArray[1] + "." + tempNumArray[2] + "." + newNum;
              this.$store.commit("versionIncrement",lastVersion);
            }
            packagingUtil.saveProductInfo(this.$store.state.productInfo,this.$store.state.spaceId,this).then((res) => {
              //this.$store.commit("updateModifyStatus",false);
              this.$store.commit("getProductInfo");
              jdiclose();
              this.executePackaging(type);
            })
          })
        }else if(type == 'preview'){
            packagingUtil.saveProductInfo(this.$store.state.productInfo,this.$store.state.spaceId,this).then((res) => {
              jdiclose();
              this.$store.commit("getProductInfo");
              this.executePackaging(type);
            })
        }
        
        /*if(this.$store.state.productInfoModify){
          packagingUtil.saveProductInfo(this.$store.state.productInfo,this.$store.state.spaceId,this).then((res) => {
            this.$store.commit("updateModifyStatus",false);
            this.$store.commit("getProductInfo");
            if(type == 'full'){
              this.checkProductVersion(packageType).then((res) => {
                jdiclose();
                this.executePackaging(type);
              }).catch((res) => {
                jdiclose();
                if(res == 'versionError'){
                  packagingUtil.myAlert("升级包的版本号不能低于已经打包的产品的版本号","提示",this);
                }
              })
            }else if(type == 'preview'){
              jdiclose();
              this.executePackaging(type);
            }
            
          })
        }else{
          if(type == 'full'){
            this.checkProductVersion(packageType).then((res) =>{
              jdiclose();
              this.executePackaging(type);
            }).catch((res) => {
              jdiclose();
              if(res == 'versionError'){
                packagingUtil.myAlert("升级包的版本号不能低于已经打包的产品的版本号","提示",this);
              }
            })
          }else if(type == 'preview'){
            jdiclose();
            this.executePackaging(type);
          }
        }*/      
      },
      executePackaging (type){
        this.dialogContent = 'packagingProgress';
        var packageType = (this.$store.state.activeOption == 'installPage' ? 'install' : 'upgrade');
        var productId = this.$store.state.productInfo.id;
        var spaceId = this.$store.state.spaceId;
        var self = this;
        this.packageComplete = false;
        this.step = 0;
        this.$refs.modal.modalAlert({
              message: {slot : true},
              title: "提示",
              callback:()=>{
                //clearInterval(self.interval);
              }
        });
        this.$axios({
            url: '/magicflu/service/s/' + spaceId + '/packages',
            method: 'post',
            data: "packageType=" + packageType + "&productId=" + productId + "&type=" + type,
            headers: {
                'Content-type': 'application/x-www-form-urlencoded'
            },
        }).then(function(response) {
            
        }).catch( function(response) {
          
        });
        this.setPackagingProgressBar();
      },
      vewPackagingProgress(){
        var self = this;
        this.setPackagingProgressBar();
        this.dialogContent = 'packagingProgress';
        this.$refs.modal.modalAlert({
              message: {slot : true},
              title: "打包进度",
              callback:function(){
                //clearInterval(self.interval);
              }
        });
      },
      previewPage (){
        this.dialogContent = 'preview';
        this.$refs.modal.modalAlert(
          {
            message: {slot : true},
            title: "预览界面"
          }
        );
      },
      setPackagingProgressBar(){
        var self = this;
        this.interval = setInterval(()=>{
          this.getPackagingStatus().then(res => {
            res = this.clearBr(res + "");
            if(res == 'complete' || res == 'fail' || res == 'cancel'){
              for(var i = 0 ; i < 9999 ;i++){
                  clearInterval(i);
              }
              this.packageComplete = true;
              if(res == 'complete'){
                packagingUtil.myAlert("打包成功","提示",self);
                this.$nextTick(() => {
                  this.packageComplete = true;
                })
              }else if(res == 'fail'){
                packagingUtil.myAlert("打包失败","提示",self);
              }else if(res == 'cancel'){
                packagingUtil.myAlert("打包任务已经取消","提示",self);
              }
              this.$refs.modal.hide();
            }else if(res == 'start'){
                this.step = this.step + 1;
                if(this.step >= 20){
                    this.step = 20;
                }
                this.packageComplete = false;
            }else{
              var logCount = parseInt(res);
              this.packageComplete = false;
              this.step = Math.round(logCount/this.logPercentNum);
              console.log(this.step);
              if(this.step >= 100){
                this.step = 99;
              }/*else if(this.step <= 10){
                 this.step = 10
              }*/
            }
          })
        },this.intervalTime)
      },
      getPackagingStatus(){
        var self = this;
        return new Promise(function(resolve, reject) {
          self.$axios({
            url: '/magicflu/html/build-package/getPackagingStatus.jsp?spaceId=' + self.$store.state.spaceId,
            method: 'get'
          }).then(response =>{
            resolve(response.data);
          }).catch(response => {});
        }) 
      },
      cancelPackaging(){
        var self = this;
        this.$axios({
            url: '/magicflu/service/s/' + self.$store.state.spaceId + '/packages/-1',
            method: 'delete'
        }).then(function(response) {
          for(var i = 0 ; i < 9999 ;i++){
            clearInterval(i);
          }
          self.packageComplete = true;
          packagingUtil.myAlert("取消打包成功","提示",self);
          self.$refs.modal.hide();
        }).catch(function(response) {});
      },
      clearBr(key) { 
        key = key.replace(/<\/?.+?>/g,""); 
        key = key.replace(/[\r\n]/g, ""); 
        return key; 
      }
  },
  computed:{
    downloadAllURL (){
      if(this.$store.state.activeOption == 'installPage'){
        return '/magicflu/service/s/' + this.$store.state.spaceId + '/packageres/' + this.$store.state.productInfo.id + '/product/installsrc.zip';
      }else{
        return '/magicflu/service/s/' + this.$store.state.spaceId + '/packageres/' + this.$store.state.productInfo.id + '/product/upgradesrc.zip';
      }
      
    }
  }
}
</script>

<style>
#installOrUpgradePage{
  padding-top:20px;
}
.page-div{
  display: flex;
  justify-content: center;
}
.page-list{
	height: 550px;
  /*width: 40%;*/
	float: left;
	margin-right: 20px;

}
.page-set{
	height: 550px;
  /*width: 40%;*/
	float: left;
}
.page-operator{
  clear: both;
  text-align: center;
}
.page-operator span{
  width: 140px;
	height: 36px;
	background-color: #f8f8f8;
	border-radius: 4px;
	border: solid 1px #333333;
  display: inline-block;
  line-height: 36px;
  margin-top: 80px;
  margin-right: 20px;
  cursor: pointer;
 
}
.page-operator>span>a{
  TEXT-DECORATION: none;
    color: #333;
    width: 100%;
    height: 100%;
    display: block;
}
@media screen and (max-width: 1023px){
  .page-operator span{
    margin-top: 20px;
  }
}
@media screen and (min-width:1024px) and (max-width: 1365px){
  .page-operator span{
    margin-top: 20px;
  }
}
@media screen and (min-width:1366px) and (max-width: 1439px){
 .page-operator span{
    margin-top: 0px;
  }
  #installOrUpgradePage {
    padding-top: 40px;
  }
  .page-list, .page-set {
    height: 500px;
  }
}
@media screen and (min-width:1440px) and (max-width:1599px){
  .page-operator span{
    margin-top: 20px;
  }
}
@media screen and (min-width:1600px) and (max-width:1919px){
  .page-operator span{
    margin-top: 20px;
  }
}
</style>